using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using NLogManager;
using WJ.DataSender.Service.Commen;
using WJ.DataSender.Service.Models;
using WJ.DataSender.Service.Models.ResultModel;

namespace WJ.DataSender.Service
{
    public class TraceRcuMitricWorker : BackgroundService
    {
        /// <summary>
        /// 消息处理引擎
        /// </summary>
        private readonly IMessageHandle<NightingaleMitricRequestModel, NightingaleResutlModel> _messageHandle;

        /// <summary>
        /// 上报周期，通过配置文件进行配置
        /// </summary>
        private int period = CacheValues.AppsettingConfig.SendPeriod;
        public TraceRcuMitricWorker(IMessageHandle<NightingaleMitricRequestModel, NightingaleResutlModel> handle)
        {
            _messageHandle = handle;
        }

        /// <summary>
        /// 开始
        /// </summary>
        /// <param name="stoppingToken"></param>
        /// <returns></returns>
        public override async Task StartAsync(CancellationToken stoppingToken)
        {
            LogHelper.Info($"当前任务-[{WorkType.RcuMitric}]-已经开始");
            await base.StartAsync(stoppingToken);
        }

        /// <summary>
        /// 正在执行
        /// </summary>
        /// <param name="stoppingToken"></param>
        /// <returns></returns>
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            LogHelper.Info($"{DateTime.Now}任务正在努力的进行中...");
            await Task.Run(async () =>
            {
                while (!stoppingToken.IsCancellationRequested)
                {
                    try
                    {
                        LogHelper.Debug($"{DateTime.Now}-调用上报RCU设备指标任务接口");

                        #region 处理上报内容
                        var mitric = new MitricModel
                        {
                            Endpoint = "192.168.1.2",
                            Metric = "cpu.util",
                            extra = "",
                            Step = 10,
                            tags = "",
                            Timestamp = CommenMethod.ConvertDateTimeToUtcs(DateTime.Now),
                            value = new Random().Next(10)
                        };
                        var content = new NightingaleMitricRequestModel();
                        content.MitricModels.Add(mitric);
                        #endregion

                        //调用上报接口
                        if (_messageHandle.StopSend)
                        {
                            LogHelper.Debug($"{_messageHandle.PlatformName}平台{WorkType.RcuMitric.Desc()}设备数据已停止上报！");
                            return;
                        }
                        var result = await _messageHandle.SendMessageAsync(HttpMethod.Post, content);
                        if (!string.IsNullOrWhiteSpace(result.Err))
                        {
                            LogHelper.Error($"{_messageHandle.PlatformName}平台{WorkType.RcuMitric.Desc()}设备数据上报失败！具体原因：【{result.Err}】");
                        }
                        else
                        {
                            LogHelper.Debug($"{_messageHandle.PlatformName}平台{WorkType.RcuMitric.Desc()}设备数据上报成功！");
                        }
                    }
                    catch (Exception ex)
                    {
                        LogHelper.Fatal($"平台对接过程中出现问题，具体问题需要查看跟踪堆栈内容！{ex.Message}", ex);
                    }
                    // 控制上报频率
                    Thread.Sleep(period);
                }
            }, stoppingToken);
        }

        public override async Task StopAsync(CancellationToken stoppingToken)
        {
            LogHelper.Info("上报RCU指标任务已经取消，正常退出！");
            await base.StopAsync(stoppingToken);
        }
    }
}
